package cn.dt70.controller;


import cn.dt70.pojo.*;
import cn.dt70.service.*;
import cn.dt70.utils.CompareDate;
import cn.dt70.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/lzy/")
public class ControllerLzy {


    @Resource
    private AqbInvestmentService aqbInvestmentService;

    @Resource
    private AqbCreditorService aqbCreditorService;

    @Resource
    private AqbProjectService aqbProjectService;

    @Resource
    private AqbProductService aqbProductService;

    @Resource
    private AqbReceptService aqbReceptService;

    @Resource
    private AqbUserService aqbUserService;


    @Resource
    private AqbRewardService aqbRewardService;

    //查看投资记录
    @RequestMapping("investment")
    public String displayInvestment(@RequestParam("id") String id,@RequestParam(value = "querytime",required = false)String querytime,@RequestParam(value = "staus",required = false)String staus,@RequestParam(value = "begin",required = false)String begin,@RequestParam(value = "end",required = false)String end,@RequestParam(value = "currentPageNo",required = false)String currentPageNo, Model model) throws Exception {

       if(querytime != null&&staus != null){
           PageSupport pageSupport = new PageSupport();
           pageSupport.setCurrentPageNo(Integer.parseInt(currentPageNo));
           List<AqbInvestment> InvestmentList = aqbInvestmentService.findByflexible(Integer.parseInt(id),Integer.parseInt(querytime),Integer.parseInt(staus),pageSupport);
           model.addAttribute("InvestmentList",InvestmentList);
           model.addAttribute("ph",pageSupport);
           return "usercenter-investcontrol-investrecord";

       }



        //一段时间内的投资
        if(begin!=null&&end!=null){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");

            PageSupport page = new PageSupport();

            page.setCurrentPageNo(Integer.parseInt(currentPageNo));
            List<AqbInvestment> InvestmentList = aqbInvestmentService.findByIdForTime(Integer.parseInt(id), simpleDateFormat.parse(begin),simpleDateFormat.parse(end),page);
            model.addAttribute("InvestmentList",InvestmentList);
            model.addAttribute("ph",page);

            return "usercenter-investcontrol-investrecord";
        }

        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(Integer.parseInt(currentPageNo));
        List<AqbInvestment> InvestmentList = aqbInvestmentService.findByflexible(Integer.parseInt(id),Integer.parseInt(querytime),Integer.parseInt(staus),pageSupport);
        model.addAttribute("InvestmentList",InvestmentList);
        model.addAttribute("ph",pageSupport);
        return "usercenter-investcontrol-investrecord";


    }


    //根据状态查询投资记录
    @RequestMapping("InvestStatus")
    public String displayInvestStatus(@RequestParam("id") String id,@RequestParam(value = "staus",required = false) String staus,Model model) throws Exception {
        if(null == staus){
            List<AqbInvestment> InvestmentList = aqbInvestmentService.findBystaus(Integer.parseInt(id),null);
            model.addAttribute("InvestmentList",InvestmentList);
            return "usercenter-investcontrol-investrecord";
        }
        List<AqbInvestment> InvestmentList = aqbInvestmentService.findBystaus(Integer.parseInt(id),Integer.parseInt(staus));
        model.addAttribute("InvestmentList",InvestmentList);
        return "usercenter-investcontrol-investrecord";
    }



    @RequestMapping("transfer")
    public String displayTransfer(@RequestParam("id") String id,Model model) throws Exception {
        List<AqbInvestment> InvestmentList = aqbInvestmentService.findCreditorById(Integer.parseInt(id),10000);
        model.addAttribute("InvestmentList",InvestmentList);
          return "usercenter-investcontrol-transfer";
    }



    //首页
    @RequestMapping("first")
    public String goFirst(@RequestParam(value = "transferStatus",required = false) String transferStatus,Model model) throws Exception {
        if(null == transferStatus) {
            List<AqbCreditor> CreditorList = aqbCreditorService.findAllCreditorById(0);
            model.addAttribute("CreditorList", CreditorList);
            return "index";
        }else{
            return "index";
        }
    }


    //添加投资记录
    @RequestMapping("addInvestment")
    public String addInvestment(@RequestParam("pid") String pid,@RequestParam("amount") String amount,@RequestParam("uid") String uid,Model model) throws Exception {
        AqbProject aqbProject = aqbProjectService.findOneProject(Integer.parseInt(pid),null);
        BigDecimal rate = aqbProject.getRate();
        Integer status= aqbProject.getProStatus();
        Date fullDate = aqbProject.getFullDate();
        Integer period = aqbProject.getPeriod();
        Date date = new Date();
        Integer restDay = 0;
        if(null != fullDate) {
            long Day = (date.getTime() - fullDate.getTime()) / 86400000;
            Integer day = (int) Day;
             restDay = period * 30 - day;
        }else{
             restDay = period * 30;
        }
        AqbInvestment aqbInvestment = new AqbInvestment();
        aqbInvestment.setProgramId(Integer.parseInt(pid));
        aqbInvestment.setInvestorId(Integer.parseInt(uid));
        aqbInvestment.setInvestAmount(Integer.parseInt(amount));
        aqbInvestment.setRestAmount(Integer.parseInt(amount));
        aqbInvestment.setRate(rate);
        aqbInvestment.setRestDay(restDay);
        aqbInvestment.setInvestDate(new Date());
        aqbInvestment.setStaus(status);
        aqbInvestmentService.addInvestment(aqbInvestment);
        List<AqbInvestment> InvestmentList = aqbInvestmentService.findById(Integer.parseInt(uid));
        aqbProjectService.modifyCurrentBids(Integer.parseInt(amount),Integer.parseInt(uid));
        if(aqbProjectService.findOneProject(Integer.parseInt(pid),null).getCurrentAmount()>=aqbProjectService.findOneProject(Integer.parseInt(pid),null).getProAmount()){
            if(aqbProjectService.modifyFullDate(new Date(),Integer.parseInt(pid))){
                System.out.println("满标日期添加成功！");
            }
            if(aqbProjectService.modifyStatus(2,Integer.parseInt(pid))){
                System.out.println("状态修改成功！");
            }
        }else{
            System.out.println("修改失败");
        }

        if(Integer.parseInt(amount)>=5000&&Integer.parseInt(amount)<10000){
            aqbUserService.modifyMoney(5000,Integer.parseInt(uid));
        }else if(Integer.parseInt(amount)>=10000&&Integer.parseInt(amount)<20000){
            aqbUserService.modifyMoney(10000,Integer.parseInt(uid));
        }else if(Integer.parseInt(amount)>=20000&&Integer.parseInt(amount)<50000){
            aqbUserService.modifyMoney(30000,Integer.parseInt(uid));
        }else if(Integer.parseInt(amount)>=50000){
            aqbUserService.modifyMoney(100000,Integer.parseInt(uid));
        }

        AqbReward rewerd = new AqbReward();
        Integer rewardMoney = (int)(Math.ceil(Integer.parseInt(amount)/100));
        rewerd.setAmount(rewardMoney);
        rewerd.setUserId(Integer.parseInt(uid));
        rewerd.setDescribe("投资");
        if(aqbRewardService.getReward(rewerd)){
            System.out.println("获得奖励金成功！");
        }

        model.addAttribute("InvestmentList",InvestmentList);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(1);
        List<AqbInvestment> InvestmentList1 = aqbInvestmentService.findByflexible(Integer.parseInt(uid),Integer.parseInt("10000"),Integer.parseInt("0"),pageSupport);
        model.addAttribute("InvestmentList",InvestmentList1);
        model.addAttribute("ph",pageSupport);
        return "usercenter-investcontrol-investrecord";
    }


    //转让债权
    @RequestMapping("TrsnsferInvestment")
    public String TrsnsferInvestment(@RequestParam("investId") String investId,Model model) throws Exception {
        AqbInvestment aqbInvestment= aqbInvestmentService.findByInvestId(Integer.parseInt(investId));
        AqbProject aqbProject = aqbProjectService.findOneProject(aqbInvestment.getProgramId(),null);
        AqbProduct aqbProduct = aqbProductService.findOneProjectDetail(aqbInvestment.getProgramId(),null);
        model.addAttribute("aqbInvestment",aqbInvestment);
        model.addAttribute("aqbProject",aqbProject);
        model.addAttribute("aqbProduct",aqbProduct);
        return "transferForm";
    }


    //添加债权转让记录
    @RequestMapping("addCreditor")
    public String addCreditor(@RequestParam("pid") String pid,@RequestParam("investor") String investor,@RequestParam("invest_money") String invest_money,@RequestParam("transfer_money") String transfer_money,@RequestParam("rate") String rate,@RequestParam("id") String id,@RequestParam("uid") String uid,Model model) throws Exception {
        AqbCreditor aqbCreditor = new AqbCreditor();
        double transferRate = Double.valueOf(invest_money)/Double.valueOf(transfer_money);
        aqbCreditor.setpId(Integer.parseInt(pid));
        aqbCreditor.setInvestId(Integer.parseInt(id));
        aqbCreditor.setInvestorId(Integer.parseInt(investor));
        aqbCreditor.setSubscribeMoney(Integer.parseInt(invest_money));
        aqbCreditor.setTransferMonry(Integer.parseInt(transfer_money));
        aqbCreditor.setTransferTime(java.sql.Date.valueOf(CompareDate.getResult(0)));
        aqbCreditor.setCurrentMoney(0);
        aqbCreditor.setTransferStatus(0);
        aqbCreditor.setRestMoney(Integer.parseInt(transfer_money));
        aqbCreditor.setReceptRate(0.0);
        double getRate = transferRate*Double.valueOf(rate);
        aqbCreditor.setGetRate(getRate);
        aqbCreditor.setCurrentRate(new BigDecimal(rate));
        aqbCreditor.setTransferRate(transferRate);
        aqbCreditorService.addCreditor(aqbCreditor);
        AqbInvestment aqbInvestment = aqbInvestmentService.findByInvestId(Integer.parseInt(id));
        System.out.println("为什么是空"+aqbInvestment.getRestAmount());
        Integer newRestAmount = aqbInvestment.getRestAmount()-Integer.parseInt(invest_money);
        System.out.println("为什么是空"+newRestAmount);
        aqbInvestment.setRestAmount(newRestAmount);
        if(aqbInvestmentService.updateInvestment(aqbInvestment)){
            System.out.println("修改投资成功！");
        }
        List<AqbInvestment> InvestmentList = aqbInvestmentService.findById(Integer.parseInt(uid));

        model.addAttribute("InvestmentList",InvestmentList);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(1);
        List<AqbInvestment> InvestmentList1 = aqbInvestmentService.findByflexible(Integer.parseInt(uid),Integer.parseInt("10000"),Integer.parseInt("0"),pageSupport);
        model.addAttribute("InvestmentList",InvestmentList1);
        model.addAttribute("ph",pageSupport);

        return "usercenter-investcontrol-investrecord";
    }

    //跳转到承接页面
    @RequestMapping("receptDetail")
    public String judgeAccept(@RequestParam("cId") String cId,Model model) throws Exception {
        AqbCreditor aqbCreditor = aqbCreditorService.findCreditorByCid(Integer.parseInt(cId));
        model.addAttribute("aqbCreditor",aqbCreditor);
          return "accept";
    }

    //债权承接
    @RequestMapping("addAccept")
    public String addAccept(@RequestParam("cid") String cid,@RequestParam("accept_money") String accept_money,@RequestParam("uid") String uid,Model model) throws Exception {
        AqbCreditor aqbCreditor = aqbCreditorService.findCreditorByCid(Integer.parseInt(cid));
        Integer currentMoney = aqbCreditor.getCurrentMoney();
        Integer newCurrentMoney = currentMoney + Integer.valueOf(accept_money);
        Integer restMoney = aqbCreditor.getRestMoney();
        Integer newRestMoney = restMoney - Integer.valueOf(accept_money);
        double sumMoney= aqbCreditor.getTransferMonry();
        double receptRate = Double.valueOf(newCurrentMoney.toString())/sumMoney;
        if(newRestMoney <= 0){
            aqbCreditor.setTransferStatus(1);
        }
        aqbCreditor.setRestMoney(newRestMoney);
        aqbCreditor.setCurrentMoney(newCurrentMoney);
        aqbCreditor.setReceptRate(receptRate);
        if(aqbCreditorService.updateCreditorById(aqbCreditor)){
            System.out.println("go on 1");
        }
        AqbRecept aqbRecept = new AqbRecept();
        aqbRecept.setpId(aqbCreditor.getpId());
        aqbRecept.setInvestorId(aqbCreditor.getInvestorId());
        aqbRecept.setcId(Integer.parseInt(cid));
        aqbRecept.setReceptId(Integer.parseInt(uid));
        System.out.println("投资id"+aqbCreditor.getInvestId());
        aqbRecept.setInvestId(aqbCreditor.getInvestId());
        aqbRecept.setReceptMoney(Integer.valueOf(accept_money));
        aqbRecept.setCurrentRate(aqbCreditor.getGetRate());
        aqbRecept.setReceptTime(new Date());
        if(aqbReceptService.addRecept(aqbRecept)){
            System.out.println("go on 2");
        }
        AqbInvestment aqbInvestment = new AqbInvestment();
        aqbInvestment.setProgramId(aqbCreditor.getpId());
        aqbInvestment.setInvestorId(Integer.parseInt(uid));
        aqbInvestment.setInvestAmount(Integer.valueOf(accept_money));
        aqbInvestment.setRestAmount(Integer.valueOf(accept_money));
        aqbInvestment.setRate(new BigDecimal(aqbCreditor.getGetRate()));
        AqbProject aqbProject = aqbProjectService.findOneProject(aqbCreditor.getpId(),null);
        Date fullDate = aqbProject.getFullDate();
        Integer period = aqbProject.getPeriod();
        Date date = new Date();
        long Day = (date.getTime()-fullDate.getTime())/86400000;
        Integer day = (int)Day;
        Integer restDay = period*30-day;
        aqbInvestment.setRestDay(restDay);
        aqbInvestment.setInvestDate(new Date());
        Integer status= aqbProject.getProStatus();
        aqbInvestment.setStaus(status);
        if(aqbInvestmentService.addInvestment(aqbInvestment)){
            System.out.println("go on 3");
        }
        List<AqbInvestment> InvestmentList = aqbInvestmentService.findById(Integer.parseInt(uid));

        model.addAttribute("InvestmentList",InvestmentList);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(1);
        List<AqbInvestment> InvestmentList1 = aqbInvestmentService.findByflexible(Integer.parseInt(uid),Integer.parseInt("10000"),Integer.parseInt("0"),pageSupport);
        model.addAttribute("InvestmentList",InvestmentList1);
        model.addAttribute("ph",pageSupport);

        return "usercenter-investcontrol-investrecord";
    }


    //查看正在转让的债权
    @RequestMapping(value = "transfering",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String displayTransfering(@RequestParam("id") String id,@RequestParam("querytime") String querytime,Model model) throws Exception {
        List<AqbCreditor>  CreditorList = aqbCreditorService.findCreditorById(Integer.parseInt(id),Integer.parseInt(querytime));
        StringBuffer sb = new StringBuffer("{");
        sb.append("\"CreditorList\":");
        String CreList = JSON.toJSONString(CreditorList);
        sb.append(CreList);
        sb.append("}");
        return sb.toString();
    }

     //查看可转让的债权
    @RequestMapping(value = "transferCan",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String displayTransferCan(@RequestParam("id") String id,@RequestParam("querytime") String querytime, Model model) throws Exception{
        List<AqbInvestment> InvestmentList = aqbInvestmentService.findCreditorById(Integer.parseInt(id),Integer.parseInt(querytime));
        StringBuffer sb = new StringBuffer("{");
        sb.append("\"InvestmentList\":");
        String CreList = JSON.toJSONString(InvestmentList);
        sb.append(CreList);
        sb.append("}");
        return sb.toString();
    }

    //查询已转让债权
    @RequestMapping(value = "transferDone",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String displayTransferDone(@RequestParam("id") String id,@RequestParam("querytime") String querytime, Model model) throws Exception {
        List<AqbCreditor>  CreditorList = aqbCreditorService.findCreditorDoneById(Integer.parseInt(id),Integer.parseInt(querytime));
        StringBuffer sb = new StringBuffer("{");
        sb.append("\"CreditorList\":");
        String CreList = JSON.toJSONString(CreditorList);
        sb.append(CreList);
        sb.append("}");
        return sb.toString();
    }

    //查询已认购债权
    @RequestMapping(value = "Subscribe",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String displaySubscribe(@RequestParam("id") String id,@RequestParam("querytime") String querytime) throws Exception {
        List<AqbRecept> receptList = aqbReceptService.findReceptById(Integer.parseInt(id),Integer.parseInt(querytime));
        StringBuffer sb = new StringBuffer("{");
        sb.append("\"receptList\":");
        String CreList = JSON.toJSONString(receptList);
        sb.append(CreList);
        sb.append("}");
        return sb.toString();
    }

    //根据日期状态查询债权
    @RequestMapping(value = "SearchByTime",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String displayByTime(@RequestParam("id") String id,@RequestParam("status") String status,@RequestParam("DateTime") String DateTime) throws Exception {
           if("0".equals(status)){
               List<AqbInvestment> InvestmentList = aqbInvestmentService.findCreditorById(Integer.parseInt(id),Integer.parseInt(DateTime));
               StringBuffer sb = new StringBuffer("{");
               sb.append("\"InvestmentList\":");
               String CreList = JSON.toJSONString(InvestmentList);
               sb.append(CreList);
               sb.append("}");
               return sb.toString();
           }else if("1".equals(status)){
               List<AqbCreditor>  CreditorList = aqbCreditorService.findCreditorById(Integer.parseInt(id),Integer.parseInt(DateTime));
               StringBuffer sb = new StringBuffer("{");
               sb.append("\"CreditorList1\":");
               String CreList = JSON.toJSONString(CreditorList);
               sb.append(CreList);
               sb.append("}");
               return sb.toString();
           }else if("2".equals(status)){
               List<AqbCreditor>  CreditorList = aqbCreditorService.findCreditorDoneById(Integer.parseInt(id),Integer.parseInt(DateTime));
               StringBuffer sb = new StringBuffer("{");
               sb.append("\"CreditorList2\":");
               String CreList = JSON.toJSONString(CreditorList);
               sb.append(CreList);
               sb.append("}");
               return sb.toString();
           }else{
               List<AqbRecept> receptList = aqbReceptService.findReceptById(Integer.parseInt(id),Integer.parseInt(DateTime));
               StringBuffer sb = new StringBuffer("{");
               sb.append("\"receptList\":");
               String CreList = JSON.toJSONString(receptList);
               sb.append(CreList);
               sb.append("}");
               return sb.toString();
           }
    }

    //查询一段时间的债权记录
    @RequestMapping(value = "SearchForTime",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String displayCreditorForTime(@RequestParam("id") String id,@RequestParam("status") String status,@RequestParam("begin") String begin,@RequestParam("end") String end) throws Exception {
        System.out.println("不知道搞定了不");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        if("0".equals(status)){
            List<AqbInvestment> InvestmentList = aqbInvestmentService.queryCreditorByIdForTime(Integer.parseInt(id),simpleDateFormat.parse(begin),simpleDateFormat.parse(end));
            StringBuffer sb = new StringBuffer("{");
            sb.append("\"InvestmentList\":");
            String CreList = JSON.toJSONString(InvestmentList);
            sb.append(CreList);
            sb.append("}");
            return sb.toString();
        }else if("1".equals(status)){
            List<AqbCreditor>  CreditorList = aqbCreditorService.findCreditorByIdForTime(Integer.parseInt(id),simpleDateFormat.parse(begin),simpleDateFormat.parse(end));
            StringBuffer sb = new StringBuffer("{");
            sb.append("\"CreditorList1\":");
            String CreList = JSON.toJSONString(CreditorList);
            sb.append(CreList);
            sb.append("}");
            return sb.toString();
        }else if("2".equals(status)){
            List<AqbCreditor>  CreditorList = aqbCreditorService.findCreditorDoneByIdForTime(Integer.parseInt(id),simpleDateFormat.parse(begin),simpleDateFormat.parse(end));
            StringBuffer sb = new StringBuffer("{");
            sb.append("\"CreditorList2\":");
            String CreList = JSON.toJSONString(CreditorList);
            sb.append(CreList);
            sb.append("}");
            return sb.toString();
        }else{
            List<AqbRecept> receptList = aqbReceptService.findReceptByIdForTime(Integer.parseInt(id),simpleDateFormat.parse(begin),simpleDateFormat.parse(end));
            StringBuffer sb = new StringBuffer("{");
            sb.append("\"receptList\":");
            String CreList = JSON.toJSONString(receptList);
            sb.append(CreList);
            sb.append("}");
            return sb.toString();
        }

    }
}


